package com.jingbian.cppccbackend.controller.user;

import org.springframework.core.io.Resource;
import com.aliyun.oss.common.utils.HttpHeaders;
import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.Proposals;
import com.jingbian.cppccbackend.entity.Result;
import com.jingbian.cppccbackend.entity.dto.PublicProposalsDTO;
import com.jingbian.cppccbackend.entity.dto.SearchProposalDTO;
import com.jingbian.cppccbackend.entity.dto.SubmitProposalsDTO;
import com.jingbian.cppccbackend.service.user.ProposalsService;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.vo.ProposalsDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;


/**
 * <p>
 * 提案信息表——用户操作 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-11
 */
@RestController
@Validated
@RequestMapping("/users/uProposals")
public class uProposalsController {

    @Autowired
    private ProposalsService proposalsService;

    /**
     * 获取某个用户的所有提案数据
     * @param searchProposalDTO
     * @return List<Proposals>
     */
    @PostMapping("/getProposalsByUserId")
    public PageInfo<Proposals> getProposalsByUserId(@RequestBody SearchProposalDTO searchProposalDTO) {
        return proposalsService.getProposalsByUserId(searchProposalDTO);
    }

    /**
     * 提案公示——所有用户愿意公示且被管理员同意公示的完结提案
     * @return List<Proposals>
     */
    @GetMapping("/getPublicProposals")
    public List<Proposals> getPublicProposals() {
        return proposalsService.getPublicProposals();
    }

    /**
     * 提案公示--含搜索分页查询
     */
    @PostMapping("/getAllPublic")
    public Result<PageInfo<Proposals>> getAllPublicProposals(@RequestBody PublicProposalsDTO publicProposalsDTO) {
        return ResultUtil.success(proposalsService.getSearchPublic(publicProposalsDTO));
    }

    /**
     * 获取某个提案的详情
     * @param proposalId 提案ID
     * @return Proposals
     */
    @GetMapping("/getProposalById/{proposalId}")
    public Proposals getProposalById(@PathVariable Integer proposalId) {
        return proposalsService.getProposalById(proposalId);
    }

    /**
     * 获取某个提案的详情 ---将提案联名的用户id转换为名字
     * @param proposalId 提案ID
     * @return ProposalsDetailVO
     */
    @GetMapping("/getById/{proposalId}")
    public ProposalsDetailVO getDetailById(@PathVariable Integer proposalId) {
        return proposalsService.getDetailById(proposalId);
    }

    /**
     * 申请取消已通过初审的提案
     * @param proposalId 提案id
     * @return Result<String>
     */
    @PutMapping("/applyCancel/{proposalId}")
    public Result<String> applyCancelProposal(@PathVariable  Integer proposalId) {
        Integer cancel = proposalsService.applyCancelProposal(proposalId);
        if (cancel==1) {
            return ResultUtil.fail("该提案不存在，无法取消！");
        }else if (cancel==2){
            return ResultUtil.fail("非提案人，不可取消！");
        }else if (cancel==3){
            return ResultUtil.success("提案取消申请成功！");
        }else if(cancel==4){
            return ResultUtil.fail("不符合条件,请操作第二个按钮");
        }else {
            return ResultUtil.fail("提案正在取消中！");
        }
    }

    /**
     * 申请提交提案 --文件附件以多列形式展开而不是Json数据，涉及表有提案表、联名人表、附件表共三表,即一次需插入三张表
     * @param proposalsDTO
     * @return
     */
    @PostMapping("submitProposals")
    public Result<String> submitProposals(@RequestBody SubmitProposalsDTO proposalsDTO) {
        proposalsService.submitProposals(proposalsDTO);
        return ResultUtil.success("提案提交成功！");
    }

    /**
     * 生成word的文件
     * @param proposalId
     * @return
     * @throws IOException
     */
    @Transactional
    @PostMapping("/wordCreate/{proposalId}")
    public ResponseEntity<Resource> wordCreate(@PathVariable Integer proposalId) throws IOException {
        ProposalsDetailVO request = proposalsService.getDetailById(proposalId);
        String signers = "无";
        if(request.getSignersName()!=null){
            signers = String.join("、", request.getSignersName());
        }
        Map<String, String> data = new HashMap<>();
        // 创建通用时间处理方法
        Function<Object, String> formatTime = time ->
                time != null ?
                        time.toString()
                                .replace("T", " ")      // 替换T为空格
                                .substring(0, 16)       // 截取前16位(2024-12-22 10:00)
                        : "";

        data.put("pid", request.getPid() != null ? request.getPid().toString() : "");
        data.put("reason", request.getCaseReason() != null ? request.getCaseReason() : "");
        data.put("uname", request.getProposer() != null ? request.getProposer() : "");
        data.put("signers", signers != null ? signers : "");
        data.put("region", request.getProposerRegion() != null ? request.getProposerRegion() : "");
        data.put("type", request.getProposalType() != null ? request.getProposalType() : "");
        data.put("submitTime", formatTime.apply(request.getSubmitTime()));
        data.put("public", request.getIsPublic() != null ? (request.getIsPublic() ? "是" : "否") : "");
        data.put("detail", request.getProposalContent() != null ? request.getProposalContent() : "");
        data.put("result", request.getHandingResult() != null ? request.getHandingResult() : "");
        data.put("status", request.getStatus() != null ? request.getStatus() : "");
        data.put("firstAuditTime", formatTime.apply(request.getFirstAuditTime()));
        data.put("recheckTime", formatTime.apply(request.getRecheckTime()));
        data.put("specialHandlingTime", formatTime.apply(request.getSpecialHandlingTime()));
        data.put("finalReplyTime", formatTime.apply(request.getFinalReplyTime()));
        data.put("completionTime", formatTime.apply(request.getCompletionTime()));

        ByteArrayResource resource = proposalsService.generateProposalDoc(data);

        // 正确返回类型
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=proposal.docx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body((Resource) resource); // 移除强制转换
    }
}